package com.cq.androidtools.jetpack.databinding

import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import com.cq.androidtools.databinding.ItemUser1Binding
import com.cq.androidtools.databinding.ItemUser2Binding
import com.cq.androidtools.databinding.ItemUser3Binding

/**
 * 作者: CQ
 * 日期: 2021-07-01
 * 说明:
 */
class UserAdapter : DataBindingMultiTypeAdapter<Person>() {

    companion object {
        private const val ITEM_DEFAULT_TYPE = 0
        private const val ITEM_STUDENT_TYPE = 1
        private const val ITEM_TEACHER_TYPE = 2
    }

    override fun getItemViewType(position: Int): Int {
        return when (getItem(position)) {
            is Student -> ITEM_STUDENT_TYPE
            is Teacher -> ITEM_TEACHER_TYPE
            else -> ITEM_DEFAULT_TYPE
        }
    }

    override fun onCreateMultiViewHolder(parent: ViewGroup, viewType: Int): ViewDataBinding {
        return when (viewType) {
            ITEM_STUDENT_TYPE -> loadLayout(ItemUser1Binding::class.java, parent)
            ITEM_TEACHER_TYPE -> loadLayout(ItemUser2Binding::class.java, parent)
            ITEM_DEFAULT_TYPE -> loadLayout(ItemUser3Binding::class.java, parent)
            else -> loadLayout(ItemUser3Binding::class.java, parent)
        }
    }

    override fun areItemsTheSame(oldItem: Person, newItem: Person): Boolean {
        return oldItem.id == newItem.id
    }

    override fun areContentsTheSame(oldItem: Person, newItem: Person, oldItemPosition: Int, newItemPosition: Int): Boolean {
        return oldItem.id == newItem.id
    }


    override fun onBindViewHolder(holder: MultiTypeViewHolder, item: Person, position: Int) {
        when (holder.binding) {
            is ItemUser1Binding -> {
                (holder.binding as ItemUser1Binding).student = getItem(position) as Student
            }
            is ItemUser2Binding -> {
                (holder.binding as ItemUser2Binding).teacher = getItem(position) as Teacher
            }
            is ItemUser3Binding -> {
                (holder.binding as ItemUser3Binding).person = getItem(position)
            }
        }

    }
}